package com.kdzy.lshy.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.kdzy.lshy.common.common.WeChat;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.codehaus.xfire.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: hanrui
 * @Date: 2018/6/16
 * @Description:
 */
public class WeChatUtils {

    public static JSONObject getOpenid(String code,WeChat weChat){

        String url = "https://api.weixin.qq.com/sns/jscode2session";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> kvList = new ArrayList<NameValuePair>();
        kvList.add(new BasicNameValuePair("appid", weChat.getAppid()));
        kvList.add(new BasicNameValuePair("secret", weChat.getApp_secrect()));
        kvList.add(new BasicNameValuePair("js_code", code));
        kvList.add(new BasicNameValuePair("grant_type", "authorization_code"));
        StringEntity entity = null;
        JSONObject result_json = new JSONObject();

       // JSONObject result = new JSONObject();

        try {
            entity = new UrlEncodedFormEntity(kvList, "utf-8");
            post.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(post);
            String string = EntityUtils.toString(response.getEntity());
            result_json = JSONObject.parseObject(string);
//          String session_key=result_json.getString("session_key");
//          result = getUserInfo(encryptedData,session_key,iv);

            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result_json;
    }

    /**
     * 解密用户敏感数据获取用户信息
     * @param sessionKey 数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv 加密算法的初始向量
     */
    private static JSONObject getUserInfo(String encryptedData,String sessionKey,String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {

            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

